﻿using System;
using System.Diagnostics;
using System.Threading;
using AyuBookmark.Common.Interfaces;

namespace AyuBookmark.Service.Services
{
    /// <summary>
    /// 浏览器活动状态监视服务
    /// </summary>
    public class BrowserObserver : IDisposable
    {
        private readonly IBookmarkManager _bookmarkManager;
        private Timer _observationTimer;
        private bool _isDisposed;

        /// <summary>
        /// 浏览器进程名称列表
        /// </summary>
        private static readonly string[] BrowserProcessNames =
        {
            "chrome",       // Google Chrome
            "msedge",       // Microsoft Edge
            "firefox",      // Mozilla Firefox
            "opera",        // Opera
            "iexplore",     // Internet Explorer
            "brave"         // Brave Browser
        };

        /// <summary>
        /// 初始化浏览器监视器
        /// </summary>
        /// <param name="bookmarkManager">书签管理器实例</param>
        public BrowserObserver(IBookmarkManager bookmarkManager)
        {
            _bookmarkManager = bookmarkManager ?? throw new ArgumentNullException(nameof(bookmarkManager));
        }

        /// <summary>
        /// 开始监视浏览器活动
        /// </summary>
        /// <param name="intervalMilliseconds">检查间隔(毫秒)</param>
        public void StartObserving(int intervalMilliseconds = 5000)
        {
            if (_observationTimer != null)
            {
                StopObserving();
            }

            _observationTimer = new Timer(CheckBrowserActivity, null, 0, intervalMilliseconds);
        }

        /// <summary>
        /// 停止监视浏览器活动
        /// </summary>
        public void StopObserving()
        {
            _observationTimer?.Dispose();
            _observationTimer = null;
        }

        /// <summary>
        /// 检查浏览器活动状态
        /// </summary>
        private void CheckBrowserActivity(object state)
        {
            try
            {
                bool isBrowserActive = IsAnyBrowserActive();
                _bookmarkManager.SetBrowserActiveState(isBrowserActive);

                if (isBrowserActive)
                {
                    string activeUrl = GetActiveBrowserUrl();
                    if (!string.IsNullOrEmpty(activeUrl))
                    {
                        _bookmarkManager.HandleCurrentUrl(activeUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                // 在实际应用中应该记录日志
                Debug.WriteLine($"Browser observation error: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查是否有浏览器处于活动状态
        /// </summary>
        /// <returns>是否检测到活动浏览器</returns>
        private bool IsAnyBrowserActive()
        {
            foreach (var processName in BrowserProcessNames)
            {
                if (IsProcessActive(processName))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 检查指定进程是否处于活动状态
        /// </summary>
        private bool IsProcessActive(string processName)
        {
            Process[] processes = Process.GetProcessesByName(processName);
            if (processes.Length == 0)
            {
                return false;
            }

            // 检查是否有窗口句柄（表示前台窗口）
            foreach (var process in processes)
            {
                if (process.MainWindowHandle != IntPtr.Zero)
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 获取活动浏览器的当前URL
        /// </summary>
        private string GetActiveBrowserUrl()
        {
            // 注意：实际实现需要根据不同的浏览器使用特定的API
            // 这里只是示例实现

            // 1. 首先获取活动窗口
            IntPtr foregroundWindow = NativeMethods.GetForegroundWindow();
            if (foregroundWindow == IntPtr.Zero)
            {
                return null;
            }

            // 2. 获取进程名
            NativeMethods.GetWindowThreadProcessId(foregroundWindow, out uint processId);
            using (Process process = Process.GetProcessById((int)processId))
            {
                if (Array.Exists(BrowserProcessNames, p => p.Equals(process.ProcessName, StringComparison.OrdinalIgnoreCase)))
                {
                    // 3. 这里应该调用特定浏览器的扩展API获取URL
                    // 示例返回空，实际项目需要实现具体逻辑
                    return string.Empty;
                }
            }

            return null;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                if (disposing)
                {
                    StopObserving();
                }
                _isDisposed = true;
            }
        }

        ~BrowserObserver()
        {
            Dispose(false);
        }
    }

    /// <summary>
    /// 原生方法封装
    /// </summary>
    internal static class NativeMethods
    {
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();

        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
    }
}